<template>
  <div class="app-container">
    <el-row :gutter="20">

      <el-col :span="4">
        <div class="training-list-container">
          <div class="training-search">
            <el-input v-model="trainingQuery" placeholder="搜索培训名称" clearable @input="searchTrainings">
              <template #prefix>
                <i class="el-input__icon el-icon-search"></i>
              </template>
            </el-input>
          </div>

          <div class="training-list">
            <el-scrollbar height="600px">
              <el-menu :default-active="selectedTrainingId" class="training-menu">
                <el-menu-item v-for="(training, index) in filteredTrainings" :key="training.trainingId"
                  :index="training.trainingId.toString()" @click="handleTrainingSelect(training)">
                  <span class="training-name">{{ training.trainingName || '未命名培训' }}</span>
                </el-menu-item>
              </el-menu>
            </el-scrollbar>
          </div>
          <div class="training-summary" align="right">
            <el-tag type="primary" effect="dark">
              总计： {{ filteredTrainings.length }} 条
            </el-tag>
          </div>
        </div>
      </el-col>
      <!-- 右侧订餐详情 -->
      <el-col :span="20">
        <el-card class="training-info-card" v-if="selectedTraining" shadow="hover">
          <template #header>
            <div class="training-info-header">
              <i-ep-collection class="header-icon" />
              <div class="header-content">
                <div class="header-title">
                  {{ selectedTraining.trainingName || '未命名培训' }}
                  <span v-if="selectedTraining.startDate || selectedTraining.endDate" class="header-time"
                    style="font-size: 12px;">
                    <i-ep-timer class="time-icon" />
                    <span v-if="selectedTraining.startDate && selectedTraining.endDate" style="font-size: 12px;">
                      {{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} 至 {{
                        parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}
                    </span>
                    <span v-else-if="selectedTraining.startDate" style="font-size: 12px;">
                      {{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} 开始
                    </span>
                    <span v-else-if="selectedTraining.endDate" style="font-size: 12px;">
                      至 {{ parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </template>
          <el-descriptions :column="3" border size="small" style="width: 50%;">

            <el-descriptions-item label="培训负责人" width="100px" align="center">
              <div class="manager-info">
                <el-tag size="small" type="primary">
                  {{ selectedTraining.manager || '暂无' }}
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="电子邮箱" width="100px" align="center">
              <el-tag size="small" v-if="selectedTraining.email">{{ selectedTraining.email }}</el-tag>
              <el-tag type="info" size="small" v-else>暂无</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="联系电话" width="100px" align="center">
              <el-tag size="small" v-if="selectedTraining.phone">{{ selectedTraining.phone }}</el-tag>
              <el-tag type="info" size="small" v-else>暂无</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input v-model="queryParams.phone" placeholder="请输入员工电话" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">

          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
              v-hasPermi="['verification:verification:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['verification:verification:remove']">删除</el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['verification:verification:export']" :disabled="!selectedTrainingId">导出</el-button>
          </el-col>
          <!-- 添加显示/隐藏详情按钮 -->
          <el-col :span="1.5">
            <el-button type="info" plain :icon="showEmployeeDetails ? 'Hide' : 'View'" @click="toggleEmployeeDetails">
              {{ showEmployeeDetails ? '隐藏员工信息详情' : '显示员工信息详情' }}
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格区域 - 添加展开列功能 -->

        <!-- 表格区域 - 添加展开列功能 -->
        <el-table v-loading="loading" :data="paginatedData" @selection-change="handleSelectionChange"
          style="width: 100%" :scroll="{}">
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column label="序号" align="center" width="60">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>

          <!-- 员工姓名列 -->
          <el-table-column label="姓名" align="center" prop="employeeName" width="70" />

          <!-- 可隐藏的员工详细信息列 -->
          <el-table-column label="员工编号" align="center" prop="employeeNo" v-if="showEmployeeDetails" width="100" />
          <el-table-column label="性别" align="center" v-if="showEmployeeDetails" width="55">
            <template #default="scope">
              <span>{{ scope.row.sex === '1' ? '男' : scope.row.sex === '0' ? '女' : '未知' }} </span>
            </template>
          </el-table-column>
          <el-table-column label="部门" align="center" prop="dept" v-if="showEmployeeDetails" width="80" />
          <el-table-column label="手机号码" align="center" prop="phone" v-if="showEmployeeDetails" width="120" />
          <el-table-column label="邮箱" align="center" prop="email" v-if="showEmployeeDetails" width="180" />


          <template v-if="dateColumns.length > 0">
            <template v-for="dateCol in dateColumns" :key="dateCol.date">
              <el-table-column :label="formatDateColumnLabel(dateCol.date)" align="center" :width="180">
                <el-table-column :prop="dateCol.lunchProp" label="午餐" align="center" width="70">
                  <template #default="scope">
                    <el-tag
                      :type="getVerificationTagType(scope.row[dateCol.lunchProp + '_ordered'], scope.row[dateCol.lunchProp + '_verified'])"
                      class="no-ellipsis">
                      {{ getVerificationStatusText(scope.row[dateCol.lunchProp + '_ordered'],
                        scope.row[dateCol.lunchProp + '_verified']) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column :prop="dateCol.dinnerProp" label="晚餐" align="center" width="70">
                  <template #default="scope">
                    <el-tag
                      :type="getVerificationTagType(scope.row[dateCol.dinnerProp + '_ordered'], scope.row[dateCol.dinnerProp + '_verified'])"
                      class="no-ellipsis">
                      {{ getVerificationStatusText(scope.row[dateCol.dinnerProp + '_ordered'],
                        scope.row[dateCol.dinnerProp + '_verified']) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table-column>
            </template>
          </template>
          <template v-else>
            <el-table-column label="用餐情况" align="center">
              <template #default="scope">
                <span>暂无用餐数据</span>
              </template>
            </el-table-column>
          </template>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['verification:verification:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['verification:verification:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>


        <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
          @pagination="handlePagination" />
      </el-col>
    </el-row>

    <!-- 在 </el-dialog> 后面添加导入对话框 -->

    <!-- 添加或修改订餐管理对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="100px">
        <!-- 添加培训相关信息 -->


        <!-- 添加员工相关信息 -->
        <!-- 修改表单部分，根据新增或修改状态显示不同的字段 -->
        <!-- 添加员工相关信息 -->
        <!-- 修改表单部分，添加失去焦点事件 -->
        <el-form-item label="员工姓名" prop="employeeName">
          <el-input v-model="form.employeeName" placeholder="请输入员工姓名" disabled />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号码" disabled />
        </el-form-item>

        <!-- 部门和邮箱信息 -->
        <el-form-item label="部门" prop="dept">
          <el-select v-model="form.dept" placeholder="请选择部门" clearable disabled>
            <el-option v-for="dict in deptOptions" :key="dict.deptId" :label="dict.deptName" :value="dict.deptName" />
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" disabled />
        </el-form-item>

        <el-form-item v-if="selectedTraining && selectedTraining.startDate && selectedTraining.endDate" label="培训时间">
          <el-tag type="primary">{{ parseTime(selectedTraining.startDate, '{y}/{m}/{d}') }} - {{
            parseTime(selectedTraining.endDate, '{y}/{m}/{d}') }}</el-tag>
        </el-form-item>
        <el-form-item label="核销详情">
          <el-table :data="verificationDetailData" border size="small" :span-method="objectSpanMethod">
            <el-table-column label="日期" align="center">
              <template #default="scope">
                <!-- 显示日期 -->
                {{ scope.row.dateLabel }}
              </template>
            </el-table-column>
            <el-table-column label="餐别" align="center" width="120">
              <template #default="scope">
                <div>
                  {{ scope.row.mealType }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="是否订餐" align="center" width="120">
              <template #default="scope">
                <div>
                  <el-tag :type="scope.row.isOrdered === '1' ? 'success' : 'info'">
                    {{ scope.row.isOrdered === '1' ? '已订餐' : '未订餐' }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" width="120">
              <template #header>
                <span style="font-weight: bold;">是否核销</span>
              </template>
              <template #default="scope">
                <div>
                  <el-button :type="scope.row.isVerified === '1' ? 'success' : 'warning'" size="small"
                    @click="toggleVerificationStatus(scope.row)" :disabled="scope.row.isOrdered !== '1'">
                    {{ scope.row.isVerified === '1' ? '已核销' : '未核销' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Verification">
import { listVerification, getVerification, delVerification, exportVerificationGrouped, exportVerification, addVerification, updateVerification, voList, updateVerificationStatusByEmpAndTraining, delVerificationsByEmpAndTraining } from "@/api/verification/verification"

import { listTrainings } from "@/api/training/training"
import { getToken } from "@/utils/auth"
import { listDept } from "@/api/system/dept"
import { validateEmployee } from "@/api/employeeManagement/employeeManagement"
import { useRoute } from 'vue-router'
const { proxy } = getCurrentInstance()
const route = useRoute()
// 添加处理后的数据列表
const processedData = ref([])
const processedOrderList = ref([])
const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 控制员工详情列的显示
const showEmployeeDetails = ref(false)
// 动态日期列
const dateColumns = ref([])
// 前端分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const paginatedData = ref([])
const sys_dept_list = ref([])


// 培训相关数据
const trainings = ref([])
const trainingQuery = ref('')
const selectedTrainingId = ref(null)

const selectedTraining = ref(null)
// 在 data reactive 部分添加一个新的计算属性

// ... existing code ...
const verificationDetailData = computed(() => {
  console.log('=== 开始计算 verificationDetailData ===')

  const details = []

  // 如果没有选择培训或没有数据，则返回空数组
  console.log('检查必要数据:')
  console.log('- selectedTraining:', selectedTraining.value)
  console.log('- form.value:', form.value)
  console.log('- selectedTrainingId:', selectedTrainingId.value)

  // 优先使用form中的日期，如果不存在则使用selectedTraining中的日期
  let startDate = null
  let endDate = null

  if (form.value.startDate && form.value.endDate) {
    startDate = form.value.startDate
    endDate = form.value.endDate
    console.log('使用form中的日期:', startDate, '到', endDate)
  } else if (selectedTraining.value && selectedTraining.value.startDate && selectedTraining.value.endDate) {
    startDate = selectedTraining.value.startDate
    endDate = selectedTraining.value.endDate
    console.log('使用selectedTraining中的日期:', startDate, '到', endDate)
  } else {
    console.log('未找到有效的日期范围')
    // 如果找不到日期范围，检查form.meals中是否已有数据
    if (form.value.meals && Object.keys(form.value.meals).length > 0) {
      console.log('使用meals中的日期数据')
      // 从meals中提取日期信息
      const mealDates = [...new Set(Object.values(form.value.meals).map(meal => meal.mealDate))].sort()
      console.log('日期数据:', mealDates)
      if (mealDates.length > 0) {
        // 为已有数据创建详情项
        mealDates.forEach(date => {
          // 查找该日期的所有用餐信息（午餐和晚餐）
          const mealsForDate = Object.values(form.value.meals).filter(meal => meal.mealDate === date)

          // 确保午餐和晚餐都存在
          let lunchMeal = mealsForDate.find(meal => meal.mealType === '午餐')
          let dinnerMeal = mealsForDate.find(meal => meal.mealType === '晚餐')

          // 如果没有午餐信息，创建默认的午餐信息
          if (!lunchMeal) {
            lunchMeal = {
              mealDate: date,
              mealType: '午餐',
              isOrdered: 0,
              isVerified: 0,
              id: null,
              orderId: null
            }
          }

          // 如果没有晚餐信息，创建默认的晚餐信息
          if (!dinnerMeal) {
            dinnerMeal = {
              mealDate: date,
              mealType: '晚餐',
              isOrdered: 0,
              isVerified: 0,
              id: null,
              orderId: null
            }
          }

          // 添加午餐信息
          details.push({
            dateLabel: date,
            mealType: lunchMeal.mealType,
            isOrdered: String(lunchMeal.isOrdered),
            isVerified: String(lunchMeal.isVerified),
            id: lunchMeal.id, // 添加ID
            orderId: lunchMeal.orderId // 添加订单ID
          })

          // 添加晚餐信息
          details.push({
            dateLabel: date,
            mealType: dinnerMeal.mealType,
            isOrdered: String(dinnerMeal.isOrdered),
            isVerified: String(dinnerMeal.isVerified),
            id: dinnerMeal.id, // 添加ID
            orderId: dinnerMeal.orderId // 添加订单ID
          })
        })
        console.log('从meals生成的详情数据:', details)
        return details
      }
    }

    // 如果form.meals中没有数据，尝试从行数据中提取（处理合并后的数据）
    const row = form.value
    if (row) {
      console.log('尝试从行数据中提取用餐信息')

      // 收集所有日期和餐别信息
      const mealInfo = []
      for (const key in row) {
        if (key.endsWith('_ordered')) {
          // 提取日期和餐别信息
          const parts = key.split('_')
          if (parts.length >= 3) {
            const datePart = parts[1] // 例如: 20230319
            const mealType = parts[0] === 'lunch' ? '午餐' : '晚餐'

            // 格式化日期
            if (datePart.length === 8) {
              const year = datePart.substring(0, 4)
              const month = datePart.substring(4, 6)
              const day = datePart.substring(6, 8)
              const formattedDate = `${year}/${month}/${day}`

              // 获取对应的核销状态
              const verifiedKey = key.replace('_ordered', '_verified')
              const idKey = key.replace('_ordered', '_id') // 获取核销ID键
              const orderIdKey = key.replace('_ordered', '_orderId') // 获取订单ID键
              const isOrdered = row[key] || 0
              const isVerified = row[verifiedKey] || 0
              const id = row[idKey] || null // 获取核销ID
              const orderId = row[orderIdKey] || null // 获取订单ID

              mealInfo.push({
                date: formattedDate,
                mealType: mealType,
                isOrdered: isOrdered,
                isVerified: isVerified,
                id: id,
                orderId: orderId
              })
            }
          }
        }
      }

      // 按日期分组并创建午餐和晚餐记录
      const dates = [...new Set(mealInfo.map(item => item.date))].sort()

      dates.forEach(date => {
        // 查找该日期的午餐和晚餐信息
        const lunchItem = mealInfo.find(item => item.date === date && item.mealType === '午餐')
        const dinnerItem = mealInfo.find(item => item.date === date && item.mealType === '晚餐')

        // 添加午餐记录
        details.push({
          dateLabel: date,
          mealType: '午餐',
          isOrdered: lunchItem ? String(lunchItem.isOrdered) : '0',
          isVerified: lunchItem ? String(lunchItem.isVerified) : '0',
          id: lunchItem ? lunchItem.id : null,
          orderId: lunchItem ? lunchItem.orderId : null
        })

        // 添加晚餐记录
        details.push({
          dateLabel: date,
          mealType: '晚餐',
          isOrdered: dinnerItem ? String(dinnerItem.isOrdered) : '0',
          isVerified: dinnerItem ? String(dinnerItem.isVerified) : '0',
          id: dinnerItem ? dinnerItem.id : null,
          orderId: dinnerItem ? dinnerItem.orderId : null
        })
      })

      if (details.length > 0) {
        console.log('从行数据生成的详情数据:', details)
        return details
      }
    }

    return details
  }

  // 获取所有日期
  const allDates = getDatesBetween(startDate, endDate)
  console.log('获取到的日期范围:', allDates)

  // 为每个日期创建午餐和晚餐记录
  allDates.forEach(date => {
    const formattedDate = formatDate(date)
    console.log('处理日期:', formattedDate)

    // 查找该日期的午餐和晚餐信息
    let lunchMeal = null
    let dinnerMeal = null
    console.log('form.value.meals:', form.value.meals)
    // 遍历meals查找匹配的餐次
    if (form.value.meals) {
      for (const key in form.value.meals) {
        const meal = form.value.meals[key]
        if (meal.mealDate === formattedDate) {
          if (meal.mealType === '午餐') {
            lunchMeal = meal
          } else if (meal.mealType === '晚餐') {
            dinnerMeal = meal
          }
        }
      }
    }

    // 添加午餐记录
    details.push({
      dateLabel: formattedDate,
      mealType: '午餐',
      isOrdered: lunchMeal ? String(lunchMeal.isOrdered) : '0',
      isVerified: lunchMeal ? String(lunchMeal.isVerified) : '0',
      id: lunchMeal ? lunchMeal.id : null,
      orderId: lunchMeal ? lunchMeal.orderId : null
    })

    // 添加晚餐记录
    details.push({
      dateLabel: formattedDate,
      mealType: '晚餐',
      isOrdered: dinnerMeal ? String(dinnerMeal.isOrdered) : '0',
      isVerified: dinnerMeal ? String(dinnerMeal.isVerified) : '0',
      id: dinnerMeal ? dinnerMeal.id : null,
      orderId: dinnerMeal ? dinnerMeal.orderId : null
    })
  })

  console.log('最终生成的详情数据:', details)
  return details
})
// ... existing code ...


// 辅助函数：获取两个日期之间的所有日期
function getDatesBetween(startDateStr, endDateStr) {
  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);
  const dates = [];

  let currentDate = new Date(startDate);
  while (currentDate <= endDate) {
    dates.push(new Date(currentDate));
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return dates;
}


// 辅助函数：查找指定日期的用餐信息
function findMealInfoForDate(meals, date) {
  console.log('=== 开始查找用餐信息 ===')
  console.log('输入的meals:', meals)
  console.log('输入的date:', date)

  // 如果meals为空或不是对象，则返回null
  if (!meals || typeof meals !== 'object') {
    console.log('meals不是有效的对象')
    return null;
  }

  // 格式化日期为
  const formattedDate = formatDate(date);
  console.log('格式化后的日期(YYYY/MM/DD):', formattedDate)

  // 遍历meals对象的键值对
  for (const key in meals) {
    const meal = meals[key];
    console.log('检查key:', key, '对应的meal:', meal)

    // 检查meal是否包含mealDate字段
    if (meal && meal.mealDate) {
      console.log('发现mealDate:', meal.mealDate)

      // 直接匹配日期 (YYYY-MM-DD)
      if (meal.mealDate === formattedDate) {
        console.log('找到完全匹配的用餐信息:', meal)
        return meal;
      }
    }
  }

  // 如果没有直接匹配，尝试查找该日期的任何餐次
  for (const key in meals) {
    const meal = meals[key];
    if (meal && meal.mealDate === formatDate(date)) {
      return meal;
    }
  }

  console.log('未找到匹配的用餐信息')
  return null;
}
// ... existing code ...

// 辅助函数：格式化日期
function formatDate(date) {
  if (!date) return '';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    trainingId: null,
    empId: null,
    verificationId: null,
    trainingDateRange: null, // 日期区间
    startDate: null, // 开始日期
    endDate: null,   // 结束日期
    mealType: null,
    isOrdered: null,
    employeeName: null,
    phone: null
  },

  rules: {
    trainingName: [
      { required: true, message: "培训名称不能为空", trigger: "blur" }
    ],
    trainingDateRange: [
      { required: true, message: "培训时间不能为空", trigger: "change" }
    ],
    employeeName: [
      { required: true, message: "员工姓名不能为空", trigger: "blur" }
    ],
    employeeNo: [
      { required: true, message: "员工编号不能为空", trigger: "blur" }
    ],
    gender: [
      { required: true, message: "性别不能为空", trigger: "change" }
    ],
    dept: [
      { required: true, message: "部门不能为空", trigger: "blur" }
    ],
    phone: [
      { required: true, message: "手机号码不能为空", trigger: "blur" },
      { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    email: [
      { required: true, message: "邮箱不能为空", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
    ],
    mealDate: [
      { required: true, message: "用餐日期不能为空", trigger: "blur" }
    ],
    isOrdered: [
      { required: true, message: "是否订餐不能为空", trigger: "blur" }
    ],
    mealType: [
      { required: true, message: "餐别不能为空", trigger: "change" }
    ],
    isVerified: [
      { required: true, message: "核销状态不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 切换员工详情列的显示状态
const toggleEmployeeDetails = () => {
  showEmployeeDetails.value = !showEmployeeDetails.value
}

// 计算属性 - 过滤后的培训列表
const filteredTrainings = computed(() => {
  if (!trainingQuery.value) {
    return trainings.value
  }
  return trainings.value.filter(training =>
    (training.trainingName || '未命名培训').includes(trainingQuery.value)
  )
})

// 获取培训列表
const getTrainings = async () => {
  try {
    const response = await listTrainings({ pageSize: 999999 })
    console.log('培训列表响应数据:', response)

    // 确保数据格式正确
    const data = response.data?.rows || response.data || response.rows || []

    if (!Array.isArray(data)) {
      console.warn('培训列表数据格式异常，期望为数组，实际类型:', typeof data)
      trainings.value = []
      return
    }

    // 去重：使用 Map 以 trainingId 为键
    const uniqueTrainings = new Map()
    data.forEach(item => {
      // 确保 trainingId 存在
      const trainingId = item.trainingId || item.id
      const trainingName = item.trainingName || item.name || '未命名培训'

      if (trainingId) {
        uniqueTrainings.set(trainingId, {
          ...item,
          trainingId: trainingId,
          trainingName: trainingName
        })
      }
    })

    trainings.value = Array.from(uniqueTrainings.values())
    console.log('处理后的培训列表:', trainings.value)

    if (trainings.value.length > 0) {
      selectedTrainingId.value = trainings.value[0].trainingId.toString()

      // 确保DOM更新后再执行
      nextTick(() => {
        handleTrainingSelect(trainings.value[0])
      })
    }
  } catch (error) {
    console.error('获取培训列表失败:', error)
    proxy.$modal.msgError('获取培训列表失败，请检查网络或联系管理员')
    trainings.value = []
  }
}

// 搜索培训
const searchTrainings = () => {
  // 这里使用计算属性 filteredTrainings 来过滤
}
const deptOptions = ref([])
function formatDateColumnLabel(dateString) {
  // 将 YYYY-MM-DD 格式的日期转换为 "YYYY年M月D日" 格式
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}/${month}/${day}`;
}
function getDeptList() {
  listDept().then(response => {
    // 修改部门列表数据结构，使label为部门名称，value为部门名称（而不是部门ID）
    sys_dept_list.value = response.data.map(item => ({
      label: item.deptName,  // 部门名称作为显示文本
      value: item.deptName   // 部门名称作为值（与后端Employee实体类的dept字段匹配）
    }))
  }).catch(error => {
    console.error("获取部门列表失败:", error)
    proxy.$modal.msgError("获取部门列表失败")
  })
}

function getFormDeptList() {
  listDept().then(response => {
    // 修改表单中的部门选项数据结构
    deptOptions.value = response.data.map(item => ({
      deptId: item.deptId,     // 保留部门ID
      deptName: item.deptName  // 部门名称
    }))
  }).catch(error => {
    console.error("获取部门列表失败:", error)
    proxy.$modal.msgError("获取部门列表失败")
  })
}

// 选择培训
const handleTrainingSelect = (training) => {
  console.log('选择的培训:', training)
  selectedTrainingId.value = training.trainingId.toString()
  queryParams.value.trainingId = training.trainingId
  selectedTraining.value = training
  handleQuery()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 添加处理表格合并的函数
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
  // 只对第一列（日期列）进行合并
  if (columnIndex === 0) {
    // 每两天（午餐和晚餐）合并一次日期
    if (rowIndex % 2 === 0) {
      // 第一行显示合并后的单元格
      return {
        rowspan: 2,
        colspan: 1
      };
    } else {
      // 第二行隐藏单元格
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    trainingName: null,
    verificationId: null,
    trainingDateRange: null,
    employeeName: null,
    employeeNo: null,
    sex: null,
    dept: null,
    phone: null,
    email: null,
    mealDate: null,
    mealType: null,
    isOrdered: null,
    isVerified: null
  }
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  currentPage.value = 1
  if (queryParams.value.trainingDateRange && queryParams.value.trainingDateRange.length === 2) {
    queryParams.value.startDate = queryParams.value.trainingDateRange[0]
    queryParams.value.endDate = queryParams.value.trainingDateRange[1]
  } else {
    queryParams.value.startDate = null
    queryParams.value.endDate = null
  }
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置查询条件
  queryParams.value.employeeName = null
  queryParams.value.phone = null
  // 重置日期区间
  queryParams.value.trainingDateRange = null
  queryParams.value.startDate = null
  queryParams.value.endDate = null
  // 重置分页
  currentPage.value = 1
  pageSize.value = 10
  handleQuery()
}

/** 查询订餐管理列表 */
function getList() {
  if (!queryParams.value.trainingId) {
    // 如果没有选择培训，清空数据
    processedData.value = []
    paginatedData.value = []
    total.value = 0
    dateColumns.value = []
    return
  }

  loading.value = true
  // 确保 trainingId 被正确传递到后端
  const params = {
    ...queryParams.value,
    trainingId: queryParams.value.trainingId
  }

  // 获取所有数据，不进行后端分页
  params.pageNum = 1
  params.pageSize = 10000 // 设置足够大的值获取所有数据

  voList(params).then(response => {
    console.log('订餐列表响应数据:', response)
    orderList.value = response.rows
    total.value = response.total
    loading.value = false

    // 处理数据合并
    processAndMergeData(response.rows)
  }).catch((error) => {
    console.error('获取订餐列表失败:', error)
    loading.value = false
    paginatedData.value = []
  })
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加核销记录"

  // 设置当前选中的培训信息
  if (selectedTrainingId.value) {
    const selectedTraining = trainings.value.find(t => t.trainingId == selectedTrainingId.value)
    if (selectedTraining) {
      form.value.trainingName = selectedTraining.trainingName
      form.value.trainingDateRange = [selectedTraining.startDate, selectedTraining.endDate]
    }
  }

  // 初始化 meals 字段
  form.value.meals = {}
}


function handleUpdate(row) {
  console.log('=== 开始执行 handleUpdate ===')
  console.log('传入的row:', row)

  reset()
  // 检查传入的row是否是PointerEvent（说明是点击工具栏按钮触发而不是传参）
  const isPointerEvent = row instanceof PointerEvent;

  if (isPointerEvent) {
    // 工具栏修改按钮被点击
    console.log('工具栏修改按钮被点击');

    // 检查是否选择了单条记录
    if (ids.value.length !== 1) {
      proxy.$modal.msgWarning("请选择一条数据进行修改");
      return;
    }

    // 根据选中的ID查找对应的行数据
    const selectedRow = processedData.value.find(item => {
      const idToCheck = item.verificationId || item.id || item.empId;
      return idToCheck === ids.value[0];
    });

    if (!selectedRow) {
      proxy.$modal.msgError("未找到选中的数据，请刷新页面后重试");
      return;
    }

    row = selectedRow;
    console.log('找到选中的行数据:', row);
  }

  // 检查是否是合并后的数据（包含完整员工信息的行）
  if (row.employeeName && row.trainingName) {
    console.log('使用合并后的数据填充表单')

    // 对于表格中已经处理过的合并数据，直接使用行数据填充表单
    form.value = {
      ...row,
      id: row.verificationId || row.id || null // 确保表单中有正确的ID
    }

    // 处理培训日期范围
    if (row.startDate && row.endDate) {
      form.value.trainingDateRange = [row.startDate, row.endDate]
      // 确保startDate和endDate也设置在form.value上
      form.value.startDate = row.startDate
      form.value.endDate = row.endDate
    }

    // 处理性别字段映射
    if (row.sex === '1' || row.sex === '0') {
      form.value.gender = row.sex
    }

    // 初始化 meals 字段
    form.value.meals = {}

    // 从动态列字段中提取 meals 数据，根据订餐和核销状态进行处理
    dateColumns.value.forEach(col => {
      const lunchOrderedKey = col.lunchProp + '_ordered'
      const dinnerOrderedKey = col.dinnerProp + '_ordered'
      const lunchVerifiedKey = col.lunchProp + '_verified'
      const dinnerVerifiedKey = col.dinnerProp + '_verified'
      const lunchIdKey = col.lunchProp + '_id'  // 获取午餐核销ID
      const dinnerIdKey = col.dinnerProp + '_id'  // 获取晚餐核销ID
      const lunchOrderIdKey = col.lunchProp + '_orderId'  // 获取午餐订单ID
      const dinnerOrderIdKey = col.dinnerProp + '_orderId'  // 获取晚餐订单ID

      // 处理午餐
      if (row[lunchOrderedKey] !== undefined) {
        // 判断是否订餐
        if (row[lunchOrderedKey] == 1) {
          // 已订餐，判断是否核销
          if (row[lunchVerifiedKey] == 1) {
            // 已核销
            form.value.meals[col.date + '_午餐'] = {
              mealDate: col.date,
              mealType: '午餐',
              isOrdered: 1,
              isVerified: 1,
              id: row[lunchIdKey] || null,  // 获取午餐核销ID
              orderId: row[lunchOrderIdKey] || null  // 获取午餐订单ID
            }
          } else {
            // 未核销
            form.value.meals[col.date + '_午餐'] = {
              mealDate: col.date,
              mealType: '午餐',
              isOrdered: 1,
              isVerified: 0,
              id: row[lunchIdKey] || null,  // 获取午餐核销ID
              orderId: row[lunchOrderIdKey] || null  // 获取午餐订单ID
            }
          }
        } else {
          // 未订餐
          form.value.meals[col.date + '_午餐'] = {
            mealDate: col.date,
            mealType: '午餐',
            isOrdered: 0,
            isVerified: 0,
            id: row[lunchIdKey] || null,  // 获取午餐核销ID（如果有的话）
            orderId: row[lunchOrderIdKey] || null  // 获取午餐订单ID
          }
        }
      }

      // 处理晚餐
      if (row[dinnerOrderedKey] !== undefined) {
        // 判断是否订餐
        if (row[dinnerOrderedKey] == 1) {
          // 已订餐，判断是否核销
          if (row[dinnerVerifiedKey] == 1) {
            // 已核销
            form.value.meals[col.date + '_晚餐'] = {
              mealDate: col.date,
              mealType: '晚餐',
              isOrdered: 1,
              isVerified: 1,
              id: row[dinnerIdKey] || null,  // 获取晚餐核销ID
              orderId: row[dinnerOrderIdKey] || null  // 获取晚餐订单ID
            }
          } else {
            // 未核销
            form.value.meals[col.date + '_晚餐'] = {
              mealDate: col.date,
              mealType: '晚餐',
              isOrdered: 1,
              isVerified: 0,
              id: row[dinnerIdKey] || null,  // 获取晚餐核销ID
              orderId: row[dinnerOrderIdKey] || null  // 获取晚餐订单ID
            }
          }
        } else {
          // 未订餐
          form.value.meals[col.date + '_晚餐'] = {
            mealDate: col.date,
            mealType: '晚餐',
            isOrdered: 0,
            isVerified: 0,
            id: row[dinnerIdKey] || null,  // 获取晚餐核销ID（如果有的话）
            orderId: row[dinnerOrderIdKey] || null  // 获取晚餐订单ID
          }
        }
      }
    })

    open.value = true
    title.value = "修改核销管理"
  } else {
    // 即使没有明确的ID，但如果行数据中有足够的信息，我们仍然可以打开编辑窗口
    if (row.employeeName && row.trainingName && row.startDate && row.endDate) {
      console.log('使用行数据直接填充表单')

      // 使用行数据填充表单
      form.value = {
        ...row,
        id: row.verificationId || row.id || null
      }

      // 处理培训日期范围
      if (row.startDate && row.endDate) {
        form.value.trainingDateRange = [row.startDate, row.endDate]
        form.value.startDate = row.startDate
        form.value.endDate = row.endDate
      }

      // 处理性别字段映射
      if (row.sex === '1' || row.sex === '0') {
        form.value.gender = row.sex
      }

      // 初始化 meals 字段
      form.value.meals = {}

      // 从动态列字段中提取 meals 数据
      for (const key in row) {
        if (key.endsWith('_ordered')) {
          // 提取日期和餐别信息
          const parts = key.split('_')
          if (parts.length >= 3) {
            const datePart = parts[1] // 例如: 20230319
            const mealType = parts[0] === 'lunch' ? '午餐' : '晚餐'

            // 格式化日期
            if (datePart.length === 8) {
              const year = datePart.substring(0, 4)
              const month = datePart.substring(4, 6)
              const day = datePart.substring(6, 8)
              const formattedDate = `${year}-${month}-${day}`

              // 获取对应的核销状态
              const verifiedKey = key.replace('_ordered', '_verified')
              const idKey = key.replace('_ordered', '_id')  // 获取核销ID键
              const orderIdKey = key.replace('_ordered', '_orderId')  // 获取订单ID键
              const isOrdered = row[key] || 0
              const isVerified = row[verifiedKey] || 0
              const id = row[idKey] || null  // 获取核销ID
              const orderId = row[orderIdKey] || null  // 获取订单ID

              // 构建meal对象
              form.value.meals[`${formattedDate}_${mealType}`] = {
                mealDate: formattedDate,
                mealType: mealType,
                isOrdered: isOrdered,
                isVerified: isVerified,
                id: id,  // 保存核销ID
                orderId: orderId  // 保存订单ID
              }
            }
          }
        }
      }

      open.value = true
      title.value = "修改核销管理"
    } else {
      proxy.$modal.msgWarning("请选择要修改的数据")
    }
  }
}

// ... existing code ...

function getVerificationStatusText(isOrdered, isVerified) {
  // 如果isOrdered为0或null，表示未订餐
  if (!isOrdered) {
    return '未订餐';
  }
  // 如果已订餐，检查核销状态
  if (isVerified) {
    return '已核销';
  }
  return '未核销';
}

// 获取核销状态标签类型
function getVerificationTagType(isOrdered, isVerified) {
  // 如果isOrdered为0或null，表示未订餐，显示为info类型（灰色）
  if (!isOrdered) {
    return 'info';
  }
  // 如果已订餐，根据核销状态显示
  if (isVerified) {
    return 'success'; // 已核销显示绿色
  }
  return 'warning'; // 未核销显示橙色
}

// 添加切换核销状态的方法
function toggleVerificationStatus(row) {
  // 只有已订餐的才能修改核销状态
  if (row.isOrdered === '1') {
    // 切换核销状态
    row.isVerified = row.isVerified === '1' ? '0' : '1';
  }
}

function handlePageChange(page) {
  currentPage.value = page
  applyPagination(processedData.value)
}

function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  applyPagination(processedData.value)
}

// 验证员工信息
function validateEmployeeOnBlur() {
  // 只在新增时进行验证
  if (!form.value.id && form.value.employeeName && form.value.phone) {
    // 添加防抖，避免频繁调用接口
    clearTimeout(validateEmployeeOnBlur.timer);
    validateEmployeeOnBlur.timer = setTimeout(() => {
      validateEmployee({
        employeeName: form.value.employeeName,
        phone: form.value.phone
      }).then(response => {
        if (response.code === 200) {
          if (response.data && response.data.nameMismatch) {
            // 显示姓名不匹配警告
            proxy.$modal.msgWarning(response.data.message);
          }
        } else {
          // 显示错误信息
          proxy.$modal.msgError(response.msg);
        }
      }).catch(error => {
        console.error('验证员工信息失败:', error);
      });
    }, 500); // 500ms 防抖
  }
}

function submitForm() {
  console.log('=== 开始执行 submitForm ===')
  console.log('当前表单数据:', form.value)

  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      console.log('表单验证通过')

      // 处理培训时间区间数据
      const formData = { ...form.value }
      console.log('准备提交的数据:', formData)

      // 处理日期范围
      if (formData.trainingDateRange && formData.trainingDateRange.length === 2) {
        formData.startDate = formData.trainingDateRange[0]
        formData.endDate = formData.trainingDateRange[1]
      } else if (selectedTraining.value) {
        // 如果表单中没有日期范围，则从selectedTraining中获取
        formData.startDate = selectedTraining.value.startDate
        formData.endDate = selectedTraining.value.endDate
      }

      // 设置培训ID
      if (selectedTrainingId.value) {
        formData.trainingId = selectedTrainingId.value
      }

      // 从表格中获取订餐和核销状态
      if (verificationDetailData.value.length > 0) {
        console.log('发现核销详情数据:', verificationDetailData.value)

        // 使用verificationDetailData中的数据
        const meals = verificationDetailData.value.map(detail => {
          // 查找对应的订单
          let orderId = null;
          if (orderList.value) {
            const order = orderList.value.find(o =>
              o.empId === formData.empId &&
              o.mealDate === detail.dateLabel &&
              o.mealType === detail.mealType
            );
            orderId = order ? order.orderId : null;
          }

          return {
            id: detail.id || null, // 核销ID（可能为null）
            orderId: orderId, // 订单ID
            mealDate: detail.dateLabel,
            mealType: detail.mealType,
            isOrdered: parseInt(detail.isOrdered),
            isVerified: detail.isOrdered === '1' ? parseInt(detail.isVerified) : null // 未订餐则为null
          };
        });

        formData.meals = meals
        console.log('生成的meals数据:', formData.meals)
      }

      // 修改时直接提交（核销管理只有修改，没有新增）
      if (formData.meals && formData.meals.length > 0) {
        // 过滤出已订餐的记录
        const orderedMeals = formData.meals.filter(meal => meal.isOrdered === 1 && meal.orderId);
        console.log('已订餐的记录:', orderedMeals);

        // 为每个已订餐的记录创建更新或新增操作
        const updatePromises = orderedMeals.map(meal => {
          if (meal.id) {
            // 已有核销记录，更新它
            const verificationData = {
              id: meal.id,
              isVerified: meal.isVerified
            };
            console.log('准备更新核销记录:', verificationData);
            return updateVerification(verificationData);
          } else {
            // 没有核销记录，创建新的
            const verificationData = {
              orderId: meal.orderId,
              isVerified: meal.isVerified
            };
            console.log('准备新增核销记录:', verificationData);
            return addVerification(verificationData);
          }
        });

        // 如果没有需要处理的记录
        if (updatePromises.length === 0) {
          proxy.$modal.msgWarning("没有需要更新的核销信息");
          open.value = false;
          getList(); // 重新加载数据
          return;
        }

        console.log('总共需要处理的记录数:', updatePromises.length);

        // 等待所有操作完成
        Promise.all(updatePromises)
          .then(responses => {
            console.log('所有核销信息处理成功:', responses);
            proxy.$modal.msgSuccess("更新成功");
            open.value = false;
            getList(); // 重新加载数据
          })
          .catch(error => {
            console.error("更新核销信息失败:", error);
            proxy.$modal.msgError("更新失败: " + (error.message || '未知错误'));
          });
      } else {
        proxy.$modal.msgWarning("没有需要更新的核销信息");
        open.value = false;
        getList(); // 重新加载数据
      }
    }
  })
}


// 处理新增核销信息
// 处理新增核销信息
function handleAddVerification(formData) {
  console.log('处理新增核销信息:', formData);

  // 如果有meals数据，则逐个添加核销记录
  if (formData.meals && formData.meals.length > 0) {
    // 创建一个数组来存储所有添加操作的Promise
    const addPromises = formData.meals
      .filter(meal => meal.isOrdered === 1 && meal.orderId) // 只有已订餐的且有订单ID的才需要核销
      .map(meal => {
        const verificationData = {
          orderId: meal.orderId, // 必须包含订单ID
          isVerified: meal.isVerified !== null ? meal.isVerified : 0
        };
        return addVerification(verificationData);
      });

    // 如果没有需要核销的记录
    if (addPromises.length === 0) {
      proxy.$modal.msgWarning("没有需要核销的订餐信息");
      open.value = false;
      return;
    }

    // 等待所有添加操作完成
    Promise.all(addPromises)
      .then(responses => {
        console.log('所有核销信息添加成功:', responses);
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      })
      .catch(error => {
        console.error("新增核销信息失败:", error);
        proxy.$modal.msgError("新增失败: " + (error.message || '未知错误'));
      });
  } else {
    proxy.$modal.msgWarning("没有需要核销的订餐信息");
    open.value = false;
  }
}

function handleDelete(row) {
  console.log('=== 删除操作开始 ===');
  console.log('传入的行数据:', row);
  console.log('ids.value:', ids.value);
  console.log('selectedTrainingId.value:', selectedTrainingId.value);
  console.log('queryParams.value.trainingId:', queryParams.value.trainingId);

  // 确定有效的培训ID
  const effectiveTrainingId = queryParams.value.trainingId || (selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null);
  console.log('有效的培训ID:', effectiveTrainingId);

  // 检查传入的row是否是PointerEvent（说明是直接点击按钮触发而不是传参）
  const isPointerEvent = row instanceof PointerEvent;

  if (!isPointerEvent && row) {
    // 单条记录删除（表格行中的删除按钮）
    console.log('执行单条记录删除');
    console.log('row.id:', row.id, '类型:', typeof row.id);
    console.log('row.empId:', row.empId, '类型:', typeof row.empId);
    console.log('row.trainingId:', row.trainingId, '类型:', typeof row.trainingId);

    // 检查必要字段是否存在
    if (!row.empId) {
      proxy.$modal.msgError("无法获取员工信息，请刷新页面后重试");
      console.error("删除失败：缺少员工ID", row);
      return;
    }

    // 确定有效的培训ID
    const rowTrainingId = row.trainingId || effectiveTrainingId;
    console.log('行数据中的培训ID:', rowTrainingId);

    const isSingleDelete = row.empId && rowTrainingId;
    console.log('是否可以单条删除:', isSingleDelete);
    if (!rowTrainingId) {
      proxy.$modal.msgError("无法获取培训信息，请刷新页面后重试");
      console.error("删除失败：缺少培训ID", row);
      return;
    }

    if (!isSingleDelete) {
      proxy.$modal.msgError("无法获取必要的删除信息（员工ID或培训ID缺失）");
      return;
    }

    const deleteInfo = `员工"${row.employeeName}"在培训"${row.trainingName}"中的所有核销信息`;
    console.log('准备显示删除确认信息:', deleteInfo);

    proxy.$modal.confirm('是否确认将 ' + deleteInfo + ' 设置为未核销？').then(function () {
      console.log('用户确认删除单条记录');
      console.log('参数 empId:', row.empId, 'trainingId:', rowTrainingId);
      // 确保参数是数字类型
      // 修改为更新核销状态为未核销而不是删除记录
      return updateVerificationStatusByEmpAndTraining(parseInt(row.empId), parseInt(rowTrainingId), 0);
    }).then((response) => {
      console.log('=== 单条记录设置为未核销成功 ===', response);
      // 重新加载数据
      getList();
      // 清空选中项
      ids.value = [];
      proxy.$modal.msgSuccess("设置为未核销成功");
    }).catch((error) => {
      console.log('=== 单条记录设置为未核销被拒绝或失败 ===', error);
      if (error !== "cancel") {
        console.error("操作失败:", error);
        proxy.$modal.msgError("操作失败: " + (error.message || error));
      }
    });
  } else {
    // 批量操作（工具栏中的删除按钮）
    console.log('执行批量操作');
    if (!ids || !ids.value || ids.value.length === 0) {
      proxy.$modal.msgError("请至少选择一条数据");
      return;
    }

    // 通过ID查找对应的行数据，获取员工ID列表
    // 注意：这里我们需要通过empId来查找，因为ids.value现在包含的是empId
    const selectedRows = processedData.value.filter(item => {
      const idToCheck = item.verificationId || item.id || item.empId;
      return ids.value.includes(idToCheck);
    });
    console.log('选中的行数据:', selectedRows);

    if (selectedRows.length === 0) {
      proxy.$modal.msgError("未找到选中的数据");
      return;
    }

    // 检查是否所有选中行都有员工ID和培训ID
    const validRows = selectedRows.filter(item => item.empId && (item.trainingId || effectiveTrainingId));
    if (validRows.length !== selectedRows.length) {
      proxy.$modal.msgError("部分选中数据缺少必要的操作信息（员工ID或培训ID）");
      return;
    }

    // 构建操作信息
    const employeeNames = validRows.map(item => item.employeeName).join(', ');
    const operationInfo = `${validRows.length}名员工在当前培训中的所有核销信息`;
    console.log('准备显示批量操作确认信息:', operationInfo);

    proxy.$modal.confirm('是否确认将 ' + operationInfo + ' 设置为未核销？').then(function () {
      console.log('用户确认批量操作');

      // 逐个将每个员工在当前培训中的所有核销信息设置为未核销
      const updatePromises = validRows.map(row => {
        // 使用行数据中的trainingId，如果不存在则使用页面选中的trainingId
        const trainingId = row.trainingId || effectiveTrainingId;
        console.log('将员工:', row.empId, '在培训:', trainingId, '中的核销信息设置为未核销');
        return updateVerificationStatusByEmpAndTraining(parseInt(row.empId), parseInt(trainingId), 0);
      });

      // 等待所有操作完成
      return Promise.all(updatePromises);
    }).then((responses) => {
      console.log('=== 批量设置为未核销操作成功 ===', responses);
      // 重新加载数据
      getList();
      // 清空选中项
      ids.value = [];
      proxy.$modal.msgSuccess("设置为未核销成功");
    }).catch((error) => {
      console.log('=== 批量设置为未核销操作被拒绝或失败 ===', error);
      if (error !== "cancel") {
        console.error("操作失败:", error);
        proxy.$modal.msgError("操作失败: " + (error.message || error));
      }
    });
  }
}
// 处理更新核销信息
// 处理更新核销信息
function handleUpdateVerification(formData) {
  console.log('处理更新核销信息:', formData);

  // 如果有meals数据，则逐个更新核销记录
  if (formData.meals && formData.meals.length > 0) {
    // 创建一个数组来存储所有更新操作的Promise
    const updatePromises = formData.meals
      .filter(meal => meal.id && meal.isOrdered === 1) // 只更新已有核销记录（有ID的）且已订餐的
      .map(meal => {
        // 对于更新操作，需要包含ID
        const verificationData = {
          id: meal.id, // 核销记录的ID
          isVerified: meal.isVerified !== null ? meal.isVerified : 0
        };

        return updateVerification(verificationData);
      });

    // 处理新增的核销记录（没有ID但已订餐的）
    const addPromises = formData.meals
      .filter(meal => !meal.id && meal.isOrdered === 1 && meal.orderId) // 没有ID但已订餐的且有订单ID的
      .map(meal => {
        const verificationData = {
          orderId: meal.orderId, // 必须包含订单ID
          isVerified: meal.isVerified !== null ? meal.isVerified : 0
        };
        return addVerification(verificationData);
      });

    // 合并所有操作
    const allPromises = [...updatePromises, ...addPromises];

    // 如果没有需要处理的记录
    if (allPromises.length === 0) {
      proxy.$modal.msgWarning("没有需要更新的核销信息");
      open.value = false;
      return;
    }

    // 等待所有操作完成
    Promise.all(allPromises)
      .then(responses => {
        console.log('所有核销信息处理成功:', responses);
        proxy.$modal.msgSuccess("更新成功");
        open.value = false;
        getList();
      })
      .catch(error => {
        console.error("更新核销信息失败:", error);
        proxy.$modal.msgError("更新失败: " + (error.message || '未知错误'));
      });
  } else {
    proxy.$modal.msgWarning("没有需要更新的核销信息");
    open.value = false;
  }
}

// ... existing code ...
function handleExport() {
  proxy.$modal.confirm('是否确认导出核销管理数据？').then(() => {
    // 构造导出参数 - 优先从当前页面数据中获取
    const exportParams = {};
    
    // 从当前选中的培训获取培训ID
    if (selectedTrainingId.value) {
      exportParams.trainingId = parseInt(selectedTrainingId.value);
    }
    
    // 从查询参数中获取其他筛选条件
    if (queryParams.value.employeeName) {
      exportParams.employeeName = queryParams.value.employeeName;
    }
    
    if (queryParams.value.phone) {
      exportParams.phone = queryParams.value.phone;
    }
    
    if (queryParams.value.startDate) {
      exportParams.startDate = queryParams.value.startDate;
    }
    
    if (queryParams.value.endDate) {
      exportParams.endDate = queryParams.value.endDate;
    }
    
    // 如果有选中的记录，则只导出选中的记录
    if (ids.value.length > 0) {
      exportParams.ids = ids.value.join(',');
    }
    
    // 检查是否选择了培训
    if (!exportParams.trainingId) {
      proxy.$modal.msgWarning('请先选择一个培训项目');
      return Promise.reject('no_training_selected');
    }
    
    // 在控制台显示所有导出信息
    console.log('=== 导出信息 ===');
    console.log('导出参数:', exportParams);
    console.log('完整查询参数:', queryParams.value);
    console.log('选中的培训ID:', selectedTrainingId.value);
    console.log('选中的记录ID:', ids.value);
    console.log('当前处理后的数据量:', processedData.value.length);
    
    // 检查参数类型
    console.log('exportParams 类型:', typeof exportParams);
    
    // 检查是否有循环引用
    try {
      const serialized = JSON.stringify(exportParams);
      console.log('exportParams 可以被序列化:', serialized);
    } catch (e) {
      console.error('exportParams 序列化失败:', e);
    }
    
    console.log('=== 开始调用导出接口 ===');
    console.log('接口地址: /verification/verification/exportGrouped');
    console.log('请求方法: POST');
    console.log('请求参数:', exportParams);
    
    // 使用分组导出接口，这将生成你想要的格式
    return exportVerificationGrouped(exportParams);
  }).then(response => {
    console.log('导出接口返回结果:', response);
    handleExportResponse(response);
  }).catch(error => {
    console.error('=== 导出失败 ===');
    console.error('错误详情:', error);
    if (error !== 'cancel' && error !== 'no_training_selected') {
      console.error('导出失败:', error);
      // 检查是否是无数据的情况
      if (error && error.message && error.message.includes('没有找到')) {
        proxy.$modal.msgWarning('没有找到符合条件的数据，请检查筛选条件');
      } else {
        proxy.$modal.msgError('导出失败: ' + (error.message || '未知错误'));
      }
    }
  });
}
// ... existing code ...

// 处理导出响应的独立函数
function handleExportResponse(response) {
  console.log('=== 导出响应 ===');
  console.log('导出响应:', response);
  console.log('响应类型:', typeof response);
  console.log('响应构造函数:', response?.constructor?.name);
  
  // 检查响应是否有效
  if (response) {
    console.log('响应数据存在');
    
    // 检查是否已经是Blob对象
    if (response instanceof Blob) {
      console.log('响应已经是Blob对象，直接下载');
      const filename = `核销记录_${new Date().getTime()}.xlsx`;
      saveAs(response, filename);
      return;
    }
    
    // 检查response.data是否存在且为Blob
    if (response.data instanceof Blob) {
      console.log('response.data是Blob对象，直接下载');
      const filename = `核销记录_${new Date().getTime()}.xlsx`;
      saveAs(response.data, filename);
      return;
    }
    
    // 检查响应头中的Content-Type
    let contentType = '';
    if (response.headers) {
      contentType = response.headers['content-type'] || response.headers['Content-Type'] || '';
    } else {
      // 尝试从Axios响应中获取headers
      if (response.config && response.request) {
        // 从原始请求中获取Content-Type
        const headers = response.request.getAllResponseHeaders();
        if (headers) {
          const headerLines = headers.trim().split(/[\r\n]+/);
          const headerMap = {};
          headerLines.forEach(line => {
            const parts = line.split(': ');
            const header = parts.shift();
            const value = parts.join(': ');
            headerMap[header.toLowerCase()] = value;
          });
          contentType = headerMap['content-type'] || '';
        }
      }
    }
    console.log('响应内容类型:', contentType);
    
    // 检查是否是Excel文件
    if (contentType && contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
      console.log('导出成功，准备下载文件');
      // 直接创建Blob并下载
      const blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
      const filename = `核销记录_${new Date().getTime()}.xlsx`;
      saveAs(blob, filename);
    } else if (response.data) {
      console.warn('响应内容类型不匹配，尝试解析响应');
      // 尝试解析响应数据看是否有错误信息
      if (response.data instanceof Blob) {
        const reader = new FileReader();
        reader.onload = function() {
          try {
            const text = reader.result;
            console.log('响应内容:', text);
            // 尝试解析为JSON
            const jsonData = JSON.parse(text);
            if (jsonData.code !== 200) {
              console.error('导出失败，服务器返回错误:', jsonData);
              proxy.$modal.msgError('导出失败: ' + jsonData.msg);
            }
          } catch (e) {
            // 不是JSON格式，尝试作为文件下载
            console.log('响应不是JSON格式，尝试下载');
            const filename = `核销记录_${new Date().getTime()}.xlsx`;
            saveAs(response.data, filename);
          }
        };
        reader.onerror = function() {
          console.error('读取响应内容失败');
          proxy.$modal.msgError('读取响应内容失败');
        };
        reader.readAsText(response.data);
      } else {
        // 尝试直接作为文本处理
        try {
          const jsonData = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
          if (jsonData.code !== 200) {
            console.error('导出失败，服务器返回错误:', jsonData);
            proxy.$modal.msgError('导出失败: ' + jsonData.msg);
          }
        } catch (e) {
          // 无法解析为JSON，可能是文件内容
          console.log('无法解析为JSON，尝试作为文件下载');
          // 检查是否有size属性，可能是Blob对象
          if (response.data && (response.data.size !== undefined || response.data instanceof ArrayBuffer)) {
            const blob = new Blob([response.data]);
            const filename = `核销记录_${new Date().getTime()}.xlsx`;
            saveAs(blob, filename);
          } else {
            proxy.$modal.msgError('导出失败: 未知响应格式');
          }
        }
      }
    } else {
      console.warn('导出数据为空');
      proxy.$modal.msgWarning('导出数据为空');
    }
  } else {
    console.warn('导出数据为空');
    proxy.$modal.msgWarning('导出数据为空');
  }
}
function handleExportProcessedData() {
  proxy.$modal.confirm('是否确认导出当前处理后的数据？').then(() => {
    // 检查是否有数据可导出
    if (processedData.value.length === 0) {
      proxy.$modal.msgWarning('当前没有可导出的数据');
      return Promise.reject('no_data');
    }
    
    // 创建一个包含所有处理后数据的导出请求
    // 这里我们直接导出当前页面显示的所有数据
    const exportData = {
      trainingId: selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null,
      // 可以添加其他筛选条件
      employeeName: queryParams.value.employeeName,
      phone: queryParams.value.phone,
      startDate: queryParams.value.startDate,
      endDate: queryParams.value.endDate
    };
    
    // 获取当前页面所有记录的ID
    const allIds = processedData.value.map(item => item.verificationId || item.id || item.empId);
    exportData.ids = allIds.join(',');
    
    console.log('=== 导出处理后的数据 ===');
    console.log('导出参数:', exportData);
    console.log('处理后的数据示例:', processedData.value[0]); // 打印第一条数据作为示例
    
    return exportVerification(exportData);
  }).then(response => {
    handleExportResponse(response);
  }).catch(error => {
    if (error !== 'cancel' && error !== 'no_data') {
      console.error('导出失败:', error);
      proxy.$modal.msgError('导出失败: ' + (error.message || '未知错误'));
    }
  });
}
function handleExportCurrentPage() {
  proxy.$modal.confirm('是否确认导出当前页面显示的数据？').then(() => {
    // 如果当前没有处理好的数据，提示用户
    if (processedData.value.length === 0) {
      proxy.$modal.msgWarning('当前没有可导出的数据');
      return Promise.reject('no_data');
    }
    
    // 构造参数，导出当前页面的数据
    const exportParams = {
      trainingId: selectedTrainingId.value ? parseInt(selectedTrainingId.value) : null
    };
    
    // 如果有选中的记录，则只导出选中的记录
    if (ids.value.length > 0) {
      exportParams.ids = ids.value.join(',');
    } else {
      // 否则导出当前页面所有记录（通过ID）
      const currentPageIds = processedData.value.map(item => item.verificationId || item.id || item.empId);
      exportParams.ids = currentPageIds.join(',');
    }
    
    console.log('=== 导出当前页面数据 ===');
    console.log('导出参数:', exportParams);
    console.log('导出的数据:', processedData.value);
    
    return exportVerification(exportParams);
  }).then(response => {
    handleExportResponse(response);
  }).catch(error => {
    if (error !== 'cancel' && error !== 'no_data') {
      console.error('导出失败:', error);
      proxy.$modal.msgError('导出失败: ' + (error.message || '未知错误'));
    }
  });
}

/** 导出分组数据 */
function handleExportGrouped() {
  proxy.$modal.confirm('是否确认导出分组核销数据？').then(() => {
    // 构造导出参数
    const exportParams = { ...queryParams.value };

    // 如果有选中的记录，则只导出选中的记录
    if (ids.value.length > 0) {
      exportParams.ids = ids.value.join(',');
    }

    // 添加测试日志
    console.log('=== 分组导出功能测试 ===');
    console.log('分组导出参数:', exportParams);
    console.log('queryParams.value:', queryParams.value);
    console.log('ids.value:', ids.value);

    // 检查参数类型
    console.log('exportParams 类型:', typeof exportParams);
    console.log('queryParams.value 类型:', typeof queryParams.value);

    // 检查是否有循环引用
    try {
      JSON.stringify(exportParams);
      console.log('exportParams 可以被序列化');
    } catch (e) {
      console.error('exportParams 序列化失败:', e);
    }

    return exportVerificationGrouped(exportParams);
  }).then(response => {
    console.log('分组导出响应:', response);
    proxy.download(response, `核销记录_分组_${new Date().getTime()}.xlsx`);
  }).catch(error => {
    console.error('=== 分组导出失败 ===');
    console.error('错误详情:', error);
    if (error !== 'cancel') {
      console.error('分组导出失败:', error);
      proxy.$modal.msgError('分组导出失败: ' + (error.message || error));
    }
  });
}

/** 处理订单数据，合并相同员工相同培训的订餐信息 */
function processOrderData(rawList) {
  console.log('原始数据:', rawList) // 添加日志查看原始数据

  if (!rawList || rawList.length === 0) {
    console.log('没有数据需要处理')
    return []
  }

  // 创建一个映射来存储合并后的数据
  const mergedMap = new Map()

  // 收集所有日期
  const dateSet = new Set()

  rawList.forEach((item, index) => {
    // console.log(`处理第${index}条数据:`, item) // 查看每条数据

    // 创建唯一键值（培训名称+员工编号+开始结束日期）
    const key = `${item.trainingName || ''}_${item.employeeNo || ''}_${item.startDate || ''}_${item.endDate || ''}`
    console.log('生成的key:', key)

    // 收集所有日期
    if (item.mealDetails) {
      item.mealDetails.forEach(detail => {
        if (detail.mealDate) {
          dateSet.add(detail.mealDate)
        }
      })
    }

    if (!mergedMap.has(key)) {
      // 如果还没有这个键值，创建一个新的合并项
      mergedMap.set(key, {
        ...item,
        mealMap: new Map() // 用于存储日期和餐别的映射
      })
    }

    // 添加mealDetails到mealMap中
    const existingItem = mergedMap.get(key)
    if (item.mealDetails) {
      item.mealDetails.forEach(detail => {
        const mealKey = `${detail.mealDate}_${detail.mealType}`
        existingItem.mealMap.set(mealKey, detail.isOrdered)
      })
    }
  })

  console.log('合并后的map:', mergedMap)
  console.log('所有日期:', dateSet)

  // 生成日期列
  const sortedDates = Array.from(dateSet).sort()
  console.log('排序后的日期:', sortedDates)

  dateColumns.value = sortedDates.map(date => {
    const dateObj = new Date(date)
    const month = dateObj.getMonth() + 1
    const day = dateObj.getDate()
    const formattedDate = `${month}月${day}日`
    const dateKey = date.replace(/-/g, '') // 例如: 20230319

    return {
      date: date,
      label: formattedDate,
      lunchProp: `lunch_${dateKey}`,
      dinnerProp: `dinner_${dateKey}`
    }
  })

  console.log('生成的日期列:', dateColumns.value)

  // 转换为数组并处理mealMap为具体字段
  const result = Array.from(mergedMap.values()).map((item, index) => {
    console.log(`处理合并项${index}:`, item)

    // 初始化所有日期字段为'0'
    const processedItem = { ...item }

    dateColumns.value.forEach(col => {
      processedItem[col.lunchProp] = '0'
      processedItem[col.dinnerProp] = '0'
    })

    // 根据mealMap设置实际值
    item.mealMap.forEach((isOrdered, mealKey) => {
      const [date, mealType] = mealKey.split('_')
      const dateKey = date.replace(/-/g, '')

      if (mealType === '午餐') {
        processedItem[`lunch_${dateKey}`] = isOrdered ? '1' : '0'
      } else if (mealType === '晚餐') {
        processedItem[`dinner_${dateKey}`] = isOrdered ? '1' : '0'
      }
    })

    // 清理不需要的字段
    delete processedItem.mealMap
    delete processedItem.mealDetails

    console.log(`处理后的项${index}:`, processedItem)
    return processedItem
  })

  console.log('最终结果:', result)
  return result
}

// 添加数据处理和合并函数
// 添加数据处理和合并函数
function processAndMergeData(rawData) {
  console.log('开始处理合并数据:', rawData)
  if (!rawData || rawData.length === 0) {
    console.log('没有数据需要处理')
    processedData.value = []
    paginatedData.value = []
    total.value = 0
    dateColumns.value = []
    return
  }

  // 用Map来合并相同员工相同培训的数据
  const mergeMap = new Map()

  // 收集所有用餐日期
  const allMealDates = new Set()

  rawData.forEach((item, index) => {
    // 收集用餐日期
    if (item.mealDate) {
      allMealDates.add(item.mealDate)
    }

    // 创建唯一标识：培训名称+员工编号+培训开始结束日期
    const uniqueKey = `${item.trainingName || '未命名培训'}_${item.employeeNo}_${item.startDate}_${item.endDate}`

    // 如果还没有这个员工的培训记录，则创建
    if (!mergeMap.has(uniqueKey)) {
      mergeMap.set(uniqueKey, {
        id: item.verificationId || item.id,
        verificationId: item.verificationId || item.id, // 明确保留verificationId
        empId: item.empId,
        employeeName: item.employeeName,
        employeeNo: item.employeeNo,
        trainingName: item.trainingName || '未命名培训',
        startDate: item.startDate,
        endDate: item.endDate,
        phone: item.phone,
        sex: item.gender === '男' ? '1' : item.gender === '女' ? '0' : '',
        dept: item.department,
        email: item.email,
        meals: {} // 用于存储用餐信息
      })
    }

    // 获取已存在的记录
    const existingRecord = mergeMap.get(uniqueKey)

    // 添加用餐详情，包括核销ID
    if (item.mealDate && item.mealType) {
      const mealKey = `${item.mealDate}_${item.mealType}`
      existingRecord.meals[mealKey] = {
        id: item.verificationId || item.id, // 核销ID
        orderId: item.orderId, // 订单ID
        isOrdered: item.isOrdered || 0,
        isVerified: item.isVerified || 0
      }
    }
  })

  // 转换Map为数组
  const mergedArray = Array.from(mergeMap.values())
  console.log('合并后的数组:', mergedArray)

  // 生成动态列信息
  const sortedDates = Array.from(allMealDates).sort()
  console.log('排序后的日期:', sortedDates)

  dateColumns.value = sortedDates.map(date => {
    const dateObj = new Date(date)
    const month = dateObj.getMonth() + 1
    const day = dateObj.getDate()
    const dateKey = date.replace(/-/g, '')

    return {
      date: date,
      label: `${month}月${day}日`,
      lunchProp: `lunch_${dateKey}`,
      dinnerProp: `dinner_${dateKey}`
    }
  })

  console.log('生成的日期列:', dateColumns.value)

  // 为每条记录添加动态列数据
  const finalData = mergedArray.map((record, index) => {
    // 先复制原记录
    const finalRecord = { ...record }

    // 初始化所有动态列
    dateColumns.value.forEach(col => {
      // 添加订餐状态字段，默认为未订餐(0)
      finalRecord[col.lunchProp + '_ordered'] = 0
      finalRecord[col.dinnerProp + '_ordered'] = 0
      // 添加核销状态字段，默认为未核销(0)
      finalRecord[col.lunchProp + '_verified'] = 0
      finalRecord[col.dinnerProp + '_verified'] = 0
      // 添加ID字段
      finalRecord[col.lunchProp + '_id'] = null
      finalRecord[col.dinnerProp + '_id'] = null
      // 添加订单ID字段
      finalRecord[col.lunchProp + '_orderId'] = null
      finalRecord[col.dinnerProp + '_orderId'] = null
    })

    // 根据实际订餐和核销情况更新值
    Object.keys(record.meals).forEach(mealKey => {
      const [date, mealType] = mealKey.split('_')
      const dateKey = date.replace(/-/g, '')
      const mealInfo = record.meals[mealKey]

      if (mealType === '午餐') {
        finalRecord[`lunch_${dateKey}_ordered`] = mealInfo.isOrdered || 0
        finalRecord[`lunch_${dateKey}_verified`] = mealInfo.isVerified || 0
        finalRecord[`lunch_${dateKey}_id`] = mealInfo.id || null  // 保存核销ID
        finalRecord[`lunch_${dateKey}_orderId`] = mealInfo.orderId || null  // 保存订单ID
      } else if (mealType === '晚餐') {
        finalRecord[`dinner_${dateKey}_ordered`] = mealInfo.isOrdered || 0
        finalRecord[`dinner_${dateKey}_verified`] = mealInfo.isVerified || 0
        finalRecord[`dinner_${dateKey}_id`] = mealInfo.id || null  // 保存核销ID
        finalRecord[`dinner_${dateKey}_orderId`] = mealInfo.orderId || null  // 保存订单ID
      }
    })

    // 删除临时属性
    delete finalRecord.meals

    console.log(`处理后的第${index}条记录:`, finalRecord)
    return finalRecord
  })

  console.log('最终数据:', finalData)

  // 保存处理后的数据
  processedData.value = finalData
  total.value = finalData.length

  // 应用前端分页
  applyFrontendPagination()

  console.log('处理完成，总记录数:', total.value)
}
// 添加前端分页函数
function applyFrontendPagination() {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  paginatedData.value = processedData.value.slice(start, end)
}

// 添加分页处理函数
function handlePagination({ page, limit }) {
  currentPage.value = page
  pageSize.value = limit
  applyFrontendPagination()
}

// 保存文件的通用方法
function saveAs(response, fileName) {
  const blob = new Blob([response])
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理多选
function handleSelectionChange(selection) {
  console.log('选中的数据:', selection);
  // 使用verificationId作为主键，如果不存在则使用id，如果还不存在则使用empId
  ids.value = selection.map(item => {
    console.log('处理项:', item);
    return item.verificationId || item.id || item.empId;
  });
  console.log('提取的IDs:', ids.value);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

getDeptList()     // 用于查询条件的部门列表
getFormDeptList() // 用于表单的部门列表
getList()
// 页面加载时获取培训列表
onMounted(() => {
  getTrainings()
})
watch(() => route.fullPath, (to, from) => {
  // 当从其他模块切换到核销管理时，重新加载数据
  if (to.includes('verification') && selectedTrainingId.value) {
    // 重新获取当前选中培训的数据
    handleTrainingSelect(trainings.value.find(t => t.trainingId == selectedTrainingId.value) || selectedTraining.value)
  }
})
</script>

<style scoped>
.training-list-container {
  border: 2px solid #e5e5e5;
  border-radius: 8px;
  padding: 16px;
  background-color: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.training-search {
  margin-bottom: 16px;
}

.training-list {
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  overflow: hidden;
}

.training-menu {
  background-color: transparent;
  border: none;
}

.training-menu .el-menu-item {
  padding: 12px 16px;
  font-size: 15px;
  /* 字体大小 */
  color: #333;
  transition: all 0.2s ease;
  border-bottom: 1px solid #eee;
  /* 添加底部分隔线 */
}

.training-menu .el-menu-item:last-child {
  border-bottom: none;
  /* 最后一个项目不显示分隔线 */
}

.training-menu .el-menu-item:hover {
  background-color: #f5f5f5;
  color: #1890ff;
}

.training-menu .el-menu-item.is-active {
  background-color: #1890ff;
  color: white;
}

.training-info-card {
  margin-bottom: 15px;
}

/* 确保培训信息区域正常显示 */
.el-card__body {
  padding: 15px;
}

.training-info-card .el-row {
  line-height: 1.8;
}

.header-title {
  font-size: 20px;

}

/* 表格自适应相关样式 */
.adaptive-table {
  width: 100%;
  max-height: calc(100vh - 300px);
}


.training-menu .el-menu-item.is-active {
  background-color: #1890ff;
  color: white;
}

.training-checkbox {
  margin-right: 8px;
}

.training-index {
  margin-right: 8px;
  color: #999;
  font-size: 14px;
}

.training-name {
  flex: 1;
}

.training-info-card {
  margin-bottom: 15px;
}

/* 确保培训信息区域正常显示 */
.el-card__body {
  padding: 15px;
}

.training-info-card .el-row {
  line-height: 1.8;
}

/* 表格自适应相关样式 */
.adaptive-table {
  width: 100%;
  max-height: calc(100vh - 300px);
}

.training-summary .el-tag {
  font-weight: bold;
  font-size: 14px;
  padding: 8px 16px;
  --el-tag-bg-color: #f0f2f5;
  --el-tag-border-color: #dcdfe6;
  --el-tag-text-color: #606266;
  width: 100%;
  justify-content: right;
}




.training-summary {
  margin-bottom: 10px;
  text-align: center;
  font-weight: bold;
  color: #666;
}
</style>